package week_8;
//pp12.1 用数组实现的堆来实现队列。

import week_8.jsjf.ArrayBinaryTree;
import week_8.jsjf.HeapADT;
import week_8.jsjf.exceptions.EmptyCollectionException;

public class HeapQueue1<T> extends ArrayBinaryTree<T> implements HeapADT<T>,QueueADT<T> {

    public HeapQueue1()
    {
        super();
    }

    @Override
    public void enqueue(T element) {
        addElement(element);
    }

    @Override
    public T dequeue() {
        return removeMin();
    }

    @Override
    public T first() {
        return findMin();
    }

    @Override
    public void addElement(T obj)
    {
        if (count == tree.length)
            expandCapacity();

        tree[count] = obj;
        count++;
        modCount++;

//        if (count > 1)
//            heapifyAdd();
    }
    private void heapifyAdd()
    {
        T temp;
        int next = count - 1;

        temp = tree[next];

        while ((next != 0) &&
                (((Comparable)temp).compareTo(tree[(next-1)/2]) < 0))
        {

            tree[next] = tree[(next-1)/2];
            next = (next-1)/2;
        }

        tree[next] = temp;
    }

    @Override
    public T removeMin() throws EmptyCollectionException
    {
        if (isEmpty())
            throw new EmptyCollectionException("ArrayHeap");

        T minElement = tree[0];
        tree[0] = tree[count-1];
        tree[count-1] = null;
        String  result =" ";
        for (int i = 0; i < count-1;i++)
        {
            result += tree[i] + " ";
        }
        heapifyRemove();
        count--;
        modCount--;
        return (T) result;
    }

    private void heapifyRemove()
    {
        T temp;
        int node = 0;
        int left = 1;
        int right = 2;
        int next;

        if ((tree[left] == null) && (tree[right] == null))
            next = count;
        else if (tree[right] == null)
            next = left;
        else if (((Comparable)tree[left]).compareTo(tree[right]) < 0)
            next = left;
        else
            next = right;
        temp = tree[node];

        while ((next < count) &&
                (((Comparable)tree[next]).compareTo(temp) < 0))
        {
            tree[node] = tree[next];
            node = next;
            left = 2 * node + 1;
            right = 2 * (node + 1);
            if ((tree[left] == null) && (tree[right] == null))
                next = count;
            else if (tree[right] == null)
                next = left;
            else if (((Comparable)tree[left]).compareTo(tree[right]) < 0)
                next = left;
            else
                next = right;
        }
        tree[node] = temp;
    }

    @Override
    public T findMin() throws EmptyCollectionException
    {
        if (isEmpty())
            throw new EmptyCollectionException("ArrayHeap");

        return tree[0];
    }
}
